ActiveReports 11
Bind a Page Report to a Data Source at Run Time
ActiveReports 11 > ActiveReports User Guide > How To > Page Report/RDL Report How To > Work with Data > Bind a Page Report to a Data Source at Run Time

ActiveReports allows you to modify a data source at run time. See the following set of sample codes to connect your Page report or RDL report to a data source at run time.

To connect to an OleDB data source

Use the API to set a data source and dataset on a report at run time. These steps assume that you have already added a Page Report template and placed a Viewer control on a Windows Form in your Visual Studio project. See Adding an ActiveReport to a Project and Windows Forms Viewer for further information.

Note: You can use the code example below for the SQL, Odbc, OleDB or Oracle data source binding. To do that, modify the Data Provider Type and Connection String according to the data source.
  1. From the Visual Studio toolbox, drag and drop a Table data region onto the design surface of the report.
  2. In the Table, select the following cells and go to Properties Window to set their Value property.
    Cell Value Property
    Left Cell =Fields!ProductID.Value
    Middle Cell =Fields!InStock.Value
    Right Cell =Fields!Price.Value
  3. Go to the Visual Studio Report Menu, and select Save Layout.
  4. In the Save As window that appears navigate to your project's folder and save the layout (like RuntimeBinding.rdlx) inside the bin/debug folder.
  5. Double-click the title bar of the Windows Form to create an event-handling method for the Form_Load event.
  6. Add the following code to the handler to connect to a data source, add a dataset and to supply data in the report.

    To write the code in Visual Basic.NET

    Visual Basic.NET code. Paste INSIDE the Form_Load event.
    Copy Code
    'create an empty page report
    Dim def As New PageReport
    'load the report layout
    def.Load(New System.IO.FileInfo(Application.StartupPath + "\RuntimeBinding.rdlx"))
    'create and setup the data source
    Dim myDataSource As New GrapeCity.ActiveReports.PageReportModel.DataSource
    myDataSource.Name = "Example Data Source"
    myDataSource.ConnectionProperties.DataProvider = "OLEDB"
    myDataSource.ConnectionProperties.ConnectString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=[User Documents folder]\GrapeCity\ActiveReports 11\Samples\Data\Reels.mdb"
    'setup the dataset
    Dim myDataSet As New GrapeCity.ActiveReports.PageReportModel.DataSet()
    Dim myQuery As New GrapeCity.ActiveReports.PageReportModel.Query()
    myDataSet.Name = "Example Data Set"
    myQuery.DataSourceName = "Example Data Source"
    myQuery.CommandType = GrapeCity.ActiveReports.PageReportModel.QueryCommandType.TableDirect
    myQuery.CommandText = GrapeCity.ActiveReports.Expressions.ExpressionInfo.FromString("Product")
    myDataSet.Query = myQuery
    ' add fields
    Dim _field As New GrapeCity.ActiveReports.PageReportModel.Field("ProductID", "ProductID", Nothing)
    myDataSet.Fields.Add(_field)
    _field = New GrapeCity.ActiveReports.PageReportModel.Field("InStock", "InStock", Nothing)
    myDataSet.Fields.Add(_field)
    _field = New GrapeCity.ActiveReports.PageReportModel.Field("Price", "Price", Nothing)
    myDataSet.Fields.Add(_field)
    'bind the data source and the dataset to the report
    def.Report.DataSources.Add(myDataSource)
    def.Report.DataSets.Add(myDataSet)
    def.Run()
    Viewer1.LoadDocument(def.Document)
    

    To write the code in C#

    C# code. Paste INSIDE the Form_Load event.
    Copy Code
    //create an empty page report
    GrapeCity.ActiveReports.PageReport def = new GrapeCity.ActiveReports.PageReport();
    //load the report layout
    def.Load(new System.IO.FileInfo(Application.StartupPath + "\RuntimeBinding.rdlx"));
    //create and setup the data source
    GrapeCity.ActiveReports.PageReportModel.DataSource myDataSource = new GrapeCity.ActiveReports.PageReportModel.DataSource();
    myDataSource.Name = "Example Data Source";
    myDataSource.ConnectionProperties.DataProvider = "OLEDB";
    myDataSource.ConnectionProperties.ConnectString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=[User Documents folder]\\GrapeCity\\ActiveReports 11\\Samples\\Data\\Reels.mdb";
    //setup the dataset
    GrapeCity.ActiveReports.PageReportModel.DataSet myDataSet = new GrapeCity.ActiveReports.PageReportModel.DataSet();
    GrapeCity.ActiveReports.PageReportModel.Query myQuery = new GrapeCity.ActiveReports.PageReportModel.Query();
    myDataSet.Name = "Example Data Set";
    myQuery.DataSourceName = "Example Data Source";
    myQuery.CommandType = GrapeCity.ActiveReports.PageReportModel.QueryCommandType.TableDirect;
    myQuery.CommandText = GrapeCity.ActiveReports.Expressions.ExpressionInfo.FromString("Product");
    myDataSet.Query = myQuery;
    // add fields
    GrapeCity.ActiveReports.PageReportModel.Field _field = new
    GrapeCity.ActiveReports.PageReportModel.Field("ProductID", "ProductID", null);
    myDataSet.Fields.Add(_field);
    _field = new GrapeCity.ActiveReports.PageReportModel.Field("InStock", "InStock", null);
    myDataSet.Fields.Add(_field);
    _field = new GrapeCity.ActiveReports.PageReportModel.Field("Price", "Price", null);
    myDataSet.Fields.Add(_field);
    //bind the data source and the dataset to the report
    def.Report.DataSources.Add(myDataSource);
    def.Report.DataSets.Add(myDataSet);
    def.Run();
    viewer1.LoadDocument(def.Document);
    
  7. Press F5 to run the Application.

To connect to an unbound Data Source

To connect to unbound data sources at run time, you can use the DataSet provider or the Object provider with the LocateDataSource event. The reporting engine raises the LocateDataSource event when it needs input on the data to use.

DataSet provider

With the DataSet provider, the ConnectionString and Query settings vary depending on how you connect to data.

To use the LocateDataSource event to bind the report to data, leave the ConnectionString blank.

To bind a report to a dataset located in a file, set the ConnectionString to the path of the file, and set the Query to the DataSet table name.

Limitations of the Dataset Provider

Parent Table Fields

To request a field from a parent table, prefix the field name with the name of the relation(s) that must be traversed to navigate to the appropriate parent table. Separate field names and relations with periods.

For example, consider a main table named OrderDetails which has a parent table named Orders. A relation named Orders_OrderDetails defines the relationship between the two tables. Use a field with the syntax below to access the OrderDate from the parent table:

Orders_OrderDetails.OrderDate

Use this same technique to traverse multiple levels of table relations. For example, consider that the Orders table used in the prior example has a parent table named Customers and a relation binding the two called Customers_Orders. If the CommandText specifies the main table as OrderDetails, use the following syntax to get the CustomerName field from the parent table:

Customers_Orders.Orders_OrderDetails.CustomerName
Note: Ambiguity can occur if a field and a relation have the same name. This is not supported.

To use the Dataset Provider

You can use the API to set a dataset on a report at run time.

The Dataset provider returns a data table. All fields in the data table are available. To use the Dataset provider as a report's data source, set up a report definition and run time, and attach the page document to a LocateDataSourceEventHandler.

These steps assume that you have already added a Page Report template and placed a Viewer control on a Windows Form in your Visual Studio project. See Adding an ActiveReport to a Project and Windows Forms Viewer for further information.

  1. In the Report Explorer, go to the DataSources node and right-click to select Add Data Source.
  2. In the Report Data Source dialog that appears, set Type to DataSetProvider and close the dialog. A data source node appears in the ReportExplorer.
  3. Right-click the data source node and to select Add Data Set.
  4. In the DataSet dialog that appears select the Fields page.
  5. On the Fields page, add a fields like =Fields!ProductID.Value and =Fields!InStock.Value.
  6. Click OK to close the dialog. Nodes with the field names appear under the dataset name.
  7. From the Visual Studio toolbox ActiveReports 11 Page Report tab, drag a Table data region onto the design surface of the report.
  8. From the ReportExplorer, add the newly added fields onto cells in the detail row of the Table and save the report.
  9. In the Visual Studio Solution Explorer, right-click YourProjectName and select Add > Class.
  10. In the Add New Item window that appears, rename the class to DataLayer.cs or .vb and click Add.
  11. In the Solution Explorer, double-click the DataLayer.cs or .vb to open the code view of the class and paste the following code inside it.

    To write the code in Visual Basic.NET

    Visual Basic.NET code. Paste inside the DataLayer class.
    Copy Code
    Imports GrapeCity.ActiveReports.Expressions.ExpressionObjectModel
    Imports System.Globalization
    Imports System.Data.OleDb
    
    Friend NotInheritable Class DataLayer
        Private _datasetData As System.Data.DataSet
    
        Public Sub New()
            LoadDataToDataSet()
        End Sub
    
        Public ReadOnly Property DataSetData() As System.Data.DataSet
            Get
               Return _datasetData
            End Get
        End Property
    
        Private Sub LoadDataToDataSet()
            Dim connStr As String = "Provider=Microsoft.Jet.OLEDB.4.0;Persist Security Info=False;
                    Data Source=[User Documents folder]\\GrapeCity\\ActiveReports 11\\Samples\\Data\\Reels.mdb"
            Dim productSql As String = "SELECT top 100 * FROM Product"
    
            _datasetData = New DataSet()
            Dim conn As New OleDbConnection(connStr)
            Dim cmd As OleDbCommand = Nothing
            Dim adapter As New OleDbDataAdapter
    
           cmd = New OleDbCommand(productSql, conn)
           adapter.SelectCommand = cmd
           adapter.Fill(_datasetData, "Products")
        End Sub
    
    End Class                                                          
    

    To write the code in C#

    C# code. Paste inside the DataLayer class.
    Copy Code
    using System;
    using System.Data;
    using System.Data.OleDb;
    
    internal sealed class DataLayer
    {
        private DataSet dataSetData;
            public DataLayer()
            {
                    LoadDataToDataSet();
            }
    
            public DataSet DataSetData
            {
                    get { return dataSetData; }
            }
                    
            private void LoadDataToDataSet()
            {
            string connStr = @"Provider=Microsoft.Jet.OLEDB.4.0;Persist Security Info=False;
                    Data Source=[User Documents folder]\\GrapeCity\\ActiveReports 11\\Samples\\Data\\Reels.mdb";
            string productSql = "SELECT * From Product";
    
                    dataSetData = new DataSet();
            OleDbConnection conn = new OleDbConnection(connStr);
            OleDbCommand cmd = new OleDbCommand(productSql, conn);
            OleDbDataAdapter adapter = new OleDbDataAdapter();
            adapter.SelectCommand = cmd;
            adapter.Fill(dataSetData, "Products");
            }
    }                        
    
    Note: The DataSetDataSource sample provides context on how to create the DataLayer class, used in the code below. The DataSetDataSource sample is included in the ActiveReports installation and is located in the [UserDocumentFolder]\GrapeCity Samples\ActiveReports 11\Page Reports\RDL\API folder.
  12. Double-click the title bar of the Windows Form to create an event-handling method for the Form_Load event and add the following code to the handler.

    To write the code in Visual Basic.NET

    Visual Basic.NET code. Paste INSIDE the Form_Load event.
    Copy Code
    LoadReport()                                                       
    
    Visual Basic.NET code. Paste INSIDE the class declaration of the form.
    Copy Code
    Dim WithEvents runtime As GrapeCity.ActiveReports.Document.PageDocument
    
    Private Sub LoadReport()
        Dim rptPath As New System.IO.FileInfo("..\..\YourReportName.rdlx")
        'Create a report definition that loads an existing report.
        Dim definition As New GrapeCity.ActiveReports.PageReport(rptPath)
        'Load the report definition into a new page document.
        runtime = New GrapeCity.ActiveReports.Document.PageDocument(definition)
        'Attach the runtime to an event. This line of code creates the event shell below.
        Viewer1.LoadDocument(runtime)
    End Sub
    
    'ActiveReports raises this event when it cannot locate a report's data source in the usual ways.
    Private Sub runtime_LocateDataSource(ByVal sender As Object, ByVal args As GrapeCity.ActiveReports.LocateDataSourceEventArgs) Handles Runtime.LocateDataSource
        Dim dl = New DataLayer
        args.Data = dl.DataSetData.Tables("Products")
    End Sub
    

    To write the code in C#

    C# code. Paste INSIDE the Form_Load event.
    Copy Code
    LoadReport();                                                      
    
    C# code. Paste INSIDE the class declaration of the form.
    Copy Code
    private void LoadReport()
    
    {
       System.IO.FileInfo rptPath = new System.IO.FileInfo("..\\..\\YourReportName.rdlx");
       //Create a report definition that loads an existing report.
       GrapeCity.ActiveReports.PageReport definition = new GrapeCity.ActiveReports.PageReport(rptPath);
       //Load the report definition into a new page document.
       GrapeCity.ActiveReports.Document.PageDocument runtime = new GrapeCity.ActiveReports.Document.PageDocument(definition);
       //Attach the runtime to an event. This line of code creates the event shell below.
       runtime.LocateDataSource += new GrapeCity.ActiveReports.LocateDataSourceEventHandler(runtime_LocateDataSource);
       viewer1.LoadDocument(runtime);
    }
    
    //ActiveReports raises this event when it cannot locate a report's data source in the usual ways.
    private void runtime_LocateDataSource(object sender, GrapeCity.ActiveReports.LocateDataSourceEventArgs args)
    {
    
       DataLayer dl = new DataLayer();
       args.Data = dl.DataSetData.Tables["Products"];
    }
    

Object Provider

Use the API to bind a report data source to a collection of objects. To bind the Object provider to a report, set up a report definition and a page document, and attach the page document to a LocateDataSourceEventHandler. Create a public class which sets up a property name to which the data field can bind.

The Object provider data source must have a dataset with the Query left blank and fields that correspond to the fields of your Object provider data source. Add these fields manually in the DataSet Dialog under Fields.

When using the Object provider, always leave the report's ConnectionString blank because it uses the LocateDataSource event to bind to an Object. Set the Query to one of these values:

To use the Object Provider

These steps assume that you have already added a Page Report template and placed a Viewer control on a Windows Form in your Visual Studio project. See Adding an ActiveReport to a Project and Windows Forms Viewer for further information.

  1. In the Report Explorer, go to the DataSources node and right-click to select Add Data Source.
  2. In the Report Data Source dialog that appears, set Type to ObjectProvider and close the dialog. A data source node appears in the ReportExplorer.
  3. Right-click the data source node and in the DataSet dialog that appears select the Fields page.
  4. In the Fields page, add a field like =Fields!name.Value and click ok to close the dialog. A node with the field name appears under the dataset name.
  5. From the Visual Studio toolbox ActiveReports 11 Page Report tab, drag a Table data region onto the design surface of the report.
  6. From the ReportExplorer, add the newly added field onto a cell in the detail row of the Table.
  7. Save the report as DogReport.rdlx.
  8. In the Solution Explorer, right-click the Form and select View Code to open the Code View.
  9. In the Code View of the form, paste the following code inside the class declaration.

    To write the code in Visual Basic.NET

    Visual Basic.NET code. Paste INSIDE the class declaration of the form.
    Copy Code
    ' Create a class from which to call a property.
    Public Class dog
       Private _name As String
       Public Property name() As String
          Get
             Return _name
          End Get
          Set(ByVal value As String)
             _name = Value
          End Set
       End Property
    End Class
    ' Create an array to contain the data.
    Dim dogArray As System.Collections.ArrayList
    ' Create a method to populate the data array.
    Private Sub LoadData()
       dogArray = New System.Collections.ArrayList()
       Dim dog1 As New dog()
       dog1.name = "border collie"
       dogArray.Add(dog1)
       dog1 = New dog()
       dog1.name = "cocker spaniel"
       dogArray.Add(dog1)
       dog1 = New dog()
       dog1.name = "golden retriever"
       dogArray.Add(dog1)
       dog1 = New dog()
       dog1.name = "shar pei"
       dogArray.Add(dog1)
    End Sub
    

    To write the code in C#

    C# code. Paste INSIDE the class declaration of the form.
    Copy Code
    // Create a class from which to call a property.
    public class dog
    {
       private string _name;
       public string name
      {
          get { return _name; }
          set { _name = value; }
       }
    }
    // Create an array to contain the data.
    System.Collections.ArrayList dogArray;
    // Create a method to populate the data array.
    private void LoadData()
    {
       dogArray = new System.Collections.ArrayList();
       dog dog1 = new dog();
       dog1.name = "border collie";
       dogArray.Add(dog1);
       dog1 = new dog();
       dog1.name = "cocker spaniel";
       dogArray.Add(dog1);
       dog1 = new dog();
       dog1.name = "golden retriever";
       dogArray.Add(dog1);
       dog1 = new dog();
       dog1.name = "shar pei";
       dogArray.Add(dog1);
    }                    
    
  10. Set up the report and add a handler for the LocateDataSource event.

    To write the code in Visual Basic.NET

    Visual Basic.NET code. Paste INSIDE the Form_Load event.
    Copy Code
    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
       ' Create file info with a path to the report in your project.
       Dim fi As New System.IO.FileInfo("..\\..\\DogReport.rdlx")
       ' Create a report definition using the file info.
       Dim repDef As New GrapeCity.ActiveReports.PageReport(fi)
       ' Create a page document using the report definition.
       Dim runt As New GrapeCity.ActiveReports.Document.PageDocument(repDef)
       ' Create a LocateDataSource event for the runtime.
       AddHandler runt.LocateDataSource, AddressOf runt_LocateDataSource
      ' Display the report in the viewer. The title can be any text.
       Viewer1.LoadDocument(runt)
    End Sub
    

    To write the code in C#

    C# code. Paste INSIDE the Form_Load event.
    Copy Code
    private void Form1_Load(object sender, EventArgs e)
    {
       // Create file info with a path to the report in your project.
       System.IO.FileInfo fi = new System.IO.FileInfo("..\\..\\DogReport.rdlx");
       // Create a report definition using the file info.
       GrapeCity.ActiveReports.PageReport repDef = new GrapeCity.ActiveReports.PageReport(fi);
       // Create a page document using the report definition.
       GrapeCity.ActiveReports.Document.PageDocument runt = new GrapeCity.ActiveReports.Document.PageDocument(repDef);
       // Create a LocateDataSource event for the runtime.
       runt.LocateDataSource += new GrapeCity.ActiveReports.LocateDataSourceEventHandler(runt_LocateDataSource);
       // Display the report in the viewer. The title can be any text.
       viewer1.LoadDocument(runt);
    }
    
  11. Use the LocateDataSource event to load data from the object.

    To write the code in Visual Basic.NET

    Visual Basic.NET code. Paste INSIDE the class declaration of the form.
    Copy Code
    Private Sub runt_LocateDataSource(ByVal sender As Object, ByVal args As GrapeCity.ActiveReports.LocateDataSourceEventArgs)
       If dogArray Is Nothing Then LoadData()
       args.Data = dogArray
    End Sub
    

    To write the code in C#

    C# code. Paste INSIDE the class declaration of the form.
    Copy Code
    void runt_LocateDataSource(object sender, GrapeCity.ActiveReports.LocateDataSourceEventArgs args)
    {
       if (dogArray == null)
       {
          LoadData();
       }
       args.Data = dogArray;   
    }   
    
  12. Press F5 to run the application.
See Also

Concepts